package filter;

import util.JsonWrapper;
import util.ResponseUtil;
import util.TokenUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author fzh
 * @since 2017/10/30
 */
@WebFilter(filterName = "TokenFilter",
    urlPatterns = {"/bikes/*", "/feedback/*", "/users/*", "/activities/*", "/me/*", "/privileges/*", "/userActivities/*", "/activityUser/*", "/dealrecord/*", "/message/*", "/cyclingrecord/*", "/user/*", "/userInfo/*"})
public class TokenFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        boolean needCheck = true;
        if ("options".equalsIgnoreCase(request.getMethod())) {
            needCheck = false;
        } else if ("/bikes".equals(request.getRequestURI())) {
            if ("get".equalsIgnoreCase(request.getMethod())) {
                needCheck = false;
            }
        } else if ("/userActivities".equals(request.getRequestURI())) {
            if ("get".equalsIgnoreCase(request.getMethod())) {
                needCheck = false;
            }
        } else if ("/user".equalsIgnoreCase(request.getRequestURI())) {
            if ("put".equalsIgnoreCase(request.getMethod())) {
                needCheck = false;
            }
        }
        if (needCheck) {
            String token = request.getHeader("Authorization");
            if (token != null && TokenUtil.availableJWT(token)) {
                chain.doFilter(req, resp);
            } else {
                ResponseUtil.write(response, JsonWrapper.builder().setStatus(400).setMsg("invalid authorization value").build());
            }
        } else {
            chain.doFilter(req, resp);
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }
}
